<template>
  <div class="technology-view">
    <!-- 科技概览 -->
    <div class="tech-overview">
      <div class="overview-header">
        <h2>科技研究</h2>
        <div class="overview-actions">
          <button class="action-btn" @click="toggleTreeView">
            <span class="btn-icon">🌳</span>
            {{ treeView ? '列表视图' : '树状视图' }}
          </button>
          <button class="action-btn" @click="openResearchPlanner">
            <span class="btn-icon">📋</span>
            研究规划
          </button>
        </div>
      </div>
      
      <!-- 研究统计 -->
      <div class="tech-stats">
        <StatCard
          v-for="stat in techStats"
          :key="stat.id"
          :title="stat.title"
          :value="stat.value"
          :icon="stat.icon"
          :trend="stat.trend"
          :color="stat.color"
        />
      </div>
    </div>

    <!-- 当前研究 -->
    <div class="current-research" v-if="currentResearch">
      <div class="section-header">
        <h3>当前研究</h3>
        <div class="research-controls">
          <button class="control-btn" @click="pauseResearch">
            {{ currentResearch.paused ? '继续' : '暂停' }}
          </button>
          <button class="control-btn danger" @click="cancelResearch">
            取消研究
          </button>
        </div>
      </div>
      
      <div class="research-card current">
        <div class="research-info">
          <div class="research-icon">{{ getTechIcon(currentResearch.id) }}</div>
          <div class="research-details">
            <div class="research-name">{{ getTechName(currentResearch.id) }}</div>
            <div class="research-category">{{ getCategoryName(currentResearch.category) }}</div>
            <div class="research-description">{{ getTechDescription(currentResearch.id) }}</div>
          </div>
        </div>
        
        <div class="research-progress">
          <div class="progress-info">
            <span class="progress-text">
              {{ Math.round(currentResearch.progress) }}% 完成
            </span>
            <span class="time-remaining">
              剩余时间: {{ formatTime(currentResearch.remainingTime) }}
            </span>
          </div>
          <div class="progress-bar">
            <div 
              class="progress-fill" 
              :style="{ width: `${currentResearch.progress}%` }"
            ></div>
          </div>
        </div>
      </div>
    </div>

    <!-- 科技分类 -->
    <div class="tech-categories">
      <div class="category-tabs">
        <button
          v-for="category in categories"
          :key="category.id"
          class="category-tab"
          :class="{ active: selectedCategory === category.id }"
          @click="selectedCategory = category.id"
        >
          <span class="tab-icon">{{ category.icon }}</span>
          <span class="tab-name">{{ category.name }}</span>
          <span class="tab-count">{{ category.count }}</span>
        </button>
      </div>
    </div>

    <!-- 科技内容 -->
    <div class="tech-content">
      <!-- 树状视图 -->
      <div v-if="treeView" class="tech-tree">
        <div class="tree-container">
          <svg class="tree-svg" :viewBox="treeViewBox">
            <!-- 连接线 -->
            <g class="connections">
              <line
                v-for="connection in connections"
                :key="`${connection.from}-${connection.to}`"
                :x1="connection.x1"
                :y1="connection.y1"
                :x2="connection.x2"
                :y2="connection.y2"
                class="connection-line"
                :class="{ 
                  available: isConnectionAvailable(connection),
                  researched: isConnectionResearched(connection)
                }"
              />
            </g>
            
            <!-- 科技节点 -->
            <g class="tech-nodes">
              <g
                v-for="tech in treeNodes"
                :key="tech.id"
                class="tech-node"
                :class="getTechNodeClass(tech)"
                :transform="`translate(${tech.x}, ${tech.y})`"
                @click="selectTech(tech)"
              >
                <circle
                  class="node-circle"
                  :r="nodeRadius"
                />
                <text
                  class="node-icon"
                  :y="5"
                  text-anchor="middle"
                >
                  {{ getTechIcon(tech.id) }}
                </text>
                <text
                  class="node-name"
                  :y="nodeRadius + 20"
                  text-anchor="middle"
                >
                  {{ getTechName(tech.id) }}
                </text>
              </g>
            </g>
          </svg>
        </div>
      </div>

      <!-- 列表视图 -->
      <div v-else class="tech-list">
        <div class="list-filters">
          <select v-model="sortBy" class="sort-select">
            <option value="name">按名称排序</option>
            <option value="cost">按成本排序</option>
            <option value="category">按分类排序</option>
          </select>
          <button 
            class="filter-btn"
            :class="{ active: showOnlyAvailable }"
            @click="showOnlyAvailable = !showOnlyAvailable"
          >
            仅显示可研究
          </button>
        </div>
        
        <div class="tech-grid">
          <TechCard
            v-for="tech in filteredTechs"
            :key="tech.id"
            :tech="tech"
            :can-research="canResearch(tech)"
            :is-researched="isResearched(tech.id)"
            @research="startResearch"
            @info="showTechInfo"
          />
        </div>
      </div>
    </div>

    <!-- 研究队列 -->
    <div class="research-queue" v-if="researchQueue.length > 0">
      <div class="section-header">
        <h3>研究队列</h3>
        <button class="action-btn secondary" @click="clearQueue">
          清空队列
        </button>
      </div>
      
      <div class="queue-list">
        <div 
          v-for="(item, index) in researchQueue" 
          :key="index"
          class="queue-item"
        >
          <div class="queue-info">
            <div class="queue-icon">{{ getTechIcon(item.id) }}</div>
            <div class="queue-details">
              <div class="queue-name">{{ getTechName(item.id) }}</div>
              <div class="queue-category">{{ getCategoryName(item.category) }}</div>
            </div>
          </div>
          
          <div class="queue-cost">
            <div class="cost-item">
              <span class="cost-icon">🔬</span>
              <span class="cost-amount">{{ formatNumber(item.cost) }}</span>
            </div>
          </div>
          
          <div class="queue-actions">
            <button 
              class="action-btn small"
              @click="moveQueueItem(index, -1)"
              :disabled="index === 0"
            >
              ⬆️
            </button>
            <button 
              class="action-btn small"
              @click="moveQueueItem(index, 1)"
              :disabled="index === researchQueue.length - 1"
            >
              ⬇️
            </button>
            <button 
              class="action-btn small danger"
              @click="removeFromQueue(index)"
            >
              ❌
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 科技信息模态框 -->
    <TechInfoModal
      v-if="showInfoModal"
      :tech="selectedTech"
      @close="closeInfoModal"
      @research="startResearch"
    />
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { useTechnologyStore, useResourcesStore } from '@/stores'
import StatCard from '@/components/ui/StatCard.vue'
import TechCard from '@/components/ui/TechCard.vue'
import TechInfoModal from '@/components/ui/TechInfoModal.vue'

const technologyStore = useTechnologyStore()
const resourcesStore = useResourcesStore()

// 响应式数据
const selectedCategory = ref('all')
const treeView = ref(true)
const sortBy = ref('name')
const showOnlyAvailable = ref(false)
const showInfoModal = ref(false)
const selectedTech = ref(null)
const nodeRadius = 30
const treeViewBox = '0 0 1200 800'

// 计算属性
const categories = computed(() => [
  { 
    id: 'all', 
    name: '全部', 
    icon: '🔬', 
    count: Object.keys(technologyStore.technologies).length 
  },
  { 
    id: 'physics', 
    name: '物理学', 
    icon: '⚛️', 
    count: getTechsByCategory('physics').length 
  },
  { 
    id: 'engineering', 
    name: '工程学', 
    icon: '⚙️', 
    count: getTechsByCategory('engineering').length 
  },
  { 
    id: 'society', 
    name: '社会学', 
    icon: '🏛️', 
    count: getTechsByCategory('society').length 
  }
])

const techStats = computed(() => [
  {
    id: 'researched',
    title: '已研究',
    value: technologyStore.researchedTechs.length,
    icon: '✅',
    trend: `+${technologyStore.researchedTechs.length}`,
    color: 'green'
  },
  {
    id: 'available',
    title: '可研究',
    value: availableTechs.value.length,
    icon: '🔓',
    trend: `${availableTechs.value.length} 项`,
    color: 'blue'
  },
  {
    id: 'research_speed',
    title: '研究速度',
    value: Math.round(technologyStore.researchSpeed),
    icon: '🚀',
    trend: '+10%',
    color: 'purple'
  },
  {
    id: 'queue_size',
    title: '队列长度',
    value: technologyStore.researchQueue.length,
    icon: '📋',
    trend: technologyStore.researchQueue.length > 0 ? '进行中' : '空闲',
    color: 'orange'
  }
])

const currentResearch = computed(() => {
  return technologyStore.currentResearch
})

const researchQueue = computed(() => {
  return technologyStore.researchQueue
})

const availableTechs = computed(() => {
  return Object.values(technologyStore.technologies).filter(tech => 
    canResearch(tech) && !isResearched(tech.id)
  )
})

const filteredTechs = computed(() => {
  let techs = Object.values(technologyStore.technologies)

  // 按分类过滤
  if (selectedCategory.value !== 'all') {
    techs = techs.filter(tech => tech.category === selectedCategory.value)
  }

  // 仅显示可研究的
  if (showOnlyAvailable.value) {
    techs = techs.filter(tech => canResearch(tech) && !isResearched(tech.id))
  }

  // 排序
  techs.sort((a, b) => {
    switch (sortBy.value) {
      case 'cost':
        return (a.cost || 0) - (b.cost || 0)
      case 'category':
        return a.category.localeCompare(b.category)
      default:
        return a.name.localeCompare(b.name)
    }
  })

  return techs
})

const treeNodes = computed(() => {
  // 简化的树状布局算法
  const techs = Object.values(technologyStore.technologies)
  const nodes = []
  
  techs.forEach((tech, index) => {
    const row = Math.floor(index / 6)
    const col = index % 6
    nodes.push({
      ...tech,
      x: 100 + col * 180,
      y: 100 + row * 120
    })
  })
  
  return nodes
})

const connections = computed(() => {
  // 简化的连接线生成
  const connections = []
  const nodes = treeNodes.value
  
  nodes.forEach(node => {
    if (node.prerequisites) {
      node.prerequisites.forEach(prereq => {
        const fromNode = nodes.find(n => n.id === prereq)
        if (fromNode) {
          connections.push({
            from: prereq,
            to: node.id,
            x1: fromNode.x,
            y1: fromNode.y,
            x2: node.x,
            y2: node.y
          })
        }
      })
    }
  })
  
  return connections
})

// 方法
function getTechsByCategory(category: string) {
  return Object.values(technologyStore.technologies).filter(tech => tech.category === category)
}

function getCategoryName(category: string): string {
  const categories: Record<string, string> = {
    physics: '物理学',
    engineering: '工程学',
    society: '社会学'
  }
  return categories[category] || category
}

function getTechIcon(techId: string): string {
  const icons: Record<string, string> = {
    basic_physics: '⚛️',
    advanced_materials: '🔬',
    energy_weapons: '⚡',
    shield_technology: '🛡️',
    faster_than_light: '🚀',
    artificial_intelligence: '🤖',
    genetic_engineering: '🧬',
    quantum_computing: '💻'
  }
  return icons[techId] || '🔬'
}

function getTechName(techId: string): string {
  return technologyStore.technologies[techId]?.name || techId
}

function getTechDescription(techId: string): string {
  return technologyStore.technologies[techId]?.description || ''
}

function canResearch(tech: any): boolean {
  // 检查前置条件
  if (tech.prerequisites) {
    return tech.prerequisites.every((prereq: string) => isResearched(prereq))
  }
  return true
}

function isResearched(techId: string): boolean {
  return technologyStore.researchedTechs.includes(techId)
}

function getTechNodeClass(tech: any): string {
  if (isResearched(tech.id)) return 'researched'
  if (canResearch(tech)) return 'available'
  return 'locked'
}

function isConnectionAvailable(connection: any): boolean {
  return canResearch(technologyStore.technologies[connection.to])
}

function isConnectionResearched(connection: any): boolean {
  return isResearched(connection.from) && isResearched(connection.to)
}

function formatNumber(num: number): string {
  if (num >= 1000000) {
    return (num / 1000000).toFixed(1) + 'M'
  }
  if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'K'
  }
  return num.toString()
}

function formatTime(seconds: number): string {
  if (seconds < 60) return `${Math.floor(seconds)}秒`
  if (seconds < 3600) return `${Math.floor(seconds / 60)}分钟`
  if (seconds < 86400) return `${Math.floor(seconds / 3600)}小时`
  return `${Math.floor(seconds / 86400)}天`
}

// 事件处理
function toggleTreeView() {
  treeView.value = !treeView.value
}

function openResearchPlanner() {
  console.log('打开研究规划器')
}

function pauseResearch() {
  if (currentResearch.value) {
    technologyStore.pauseResearch()
  }
}

function cancelResearch() {
  if (confirm('确定要取消当前研究吗？')) {
    technologyStore.cancelResearch()
  }
}

function selectTech(tech: any) {
  selectedTech.value = tech
  showInfoModal.value = true
}

function startResearch(tech: any) {
  if (canResearch(tech) && !isResearched(tech.id)) {
    technologyStore.startResearch(tech.id)
  }
}

function showTechInfo(tech: any) {
  selectedTech.value = tech
  showInfoModal.value = true
}

function closeInfoModal() {
  showInfoModal.value = false
  selectedTech.value = null
}

function clearQueue() {
  if (confirm('确定要清空研究队列吗？')) {
    technologyStore.clearResearchQueue()
  }
}

function moveQueueItem(index: number, direction: number) {
  const newIndex = index + direction
  if (newIndex >= 0 && newIndex < researchQueue.value.length) {
    technologyStore.moveQueueItem(index, newIndex)
  }
}

function removeFromQueue(index: number) {
  technologyStore.removeFromQueue(index)
}
</script>

<style scoped>
.technology-view {
  padding: 1rem;
  height: 100%;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.overview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.overview-header h2 {
  margin: 0;
  color: #ffffff;
  font-size: 1.5rem;
}

.overview-actions {
  display: flex;
  gap: 0.5rem;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 1rem;
  background: #00d4ff;
  color: #000000;
  border: none;
  border-radius: 6px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
}

.action-btn:hover {
  background: #0099cc;
  transform: translateY(-1px);
}

.action-btn.secondary {
  background: rgba(255, 255, 255, 0.1);
  color: #ffffff;
}

.action-btn.secondary:hover {
  background: rgba(255, 255, 255, 0.2);
}

.action-btn.small {
  padding: 0.25rem 0.5rem;
  font-size: 0.875rem;
}

.action-btn.danger {
  background: rgba(255, 68, 68, 0.2);
  color: #ff4444;
}

.action-btn.danger:hover {
  background: #ff4444;
  color: #ffffff;
}

.btn-icon {
  font-size: 1rem;
}

.tech-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 1rem;
  margin-bottom: 1rem;
}

.current-research {
  background: rgba(0, 0, 0, 0.4);
  border: 1px solid rgba(0, 212, 255, 0.3);
  border-radius: 8px;
  padding: 1rem;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.section-header h3 {
  margin: 0;
  color: #00d4ff;
  font-size: 1.2rem;
}

.research-controls {
  display: flex;
  gap: 0.5rem;
}

.control-btn {
  padding: 0.375rem 0.75rem;
  background: rgba(255, 255, 255, 0.1);
  color: #cccccc;
  border: none;
  border-radius: 4px;
  font-size: 0.875rem;
  cursor: pointer;
  transition: all 0.2s ease;
}

.control-btn:hover {
  background: rgba(255, 255, 255, 0.2);
}

.control-btn.danger {
  background: rgba(255, 68, 68, 0.2);
  color: #ff4444;
}

.control-btn.danger:hover {
  background: #ff4444;
  color: #ffffff;
}

.research-card {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 1rem;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 6px;
}

.research-card.current {
  background: rgba(0, 212, 255, 0.1);
  border: 1px solid rgba(0, 212, 255, 0.3);
}

.research-info {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  flex: 1;
}

.research-icon {
  font-size: 2rem;
  min-width: 40px;
}

.research-details {
  flex: 1;
}

.research-name {
  font-weight: 600;
  color: #ffffff;
  margin-bottom: 0.25rem;
}

.research-category {
  font-size: 0.875rem;
  color: #00d4ff;
  margin-bottom: 0.25rem;
}

.research-description {
  font-size: 0.875rem;
  color: #cccccc;
  line-height: 1.4;
}

.research-progress {
  min-width: 200px;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.5rem;
  font-size: 0.875rem;
}

.progress-text {
  color: #ffffff;
  font-weight: 500;
}

.time-remaining {
  color: #888888;
}

.progress-bar {
  height: 8px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #00d4ff, #0099cc);
  transition: width 0.3s ease;
}

.category-tabs {
  display: flex;
  gap: 0.5rem;
  margin-bottom: 1rem;
  overflow-x: auto;
}

.category-tab {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.75rem 1rem;
  background: rgba(255, 255, 255, 0.1);
  color: #cccccc;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  white-space: nowrap;
}

.category-tab:hover {
  background: rgba(255, 255, 255, 0.2);
}

.category-tab.active {
  background: #00d4ff;
  color: #000000;
}

.tab-icon {
  font-size: 1.2rem;
}

.tab-name {
  font-weight: 500;
}

.tab-count {
  background: rgba(0, 0, 0, 0.2);
  padding: 0.125rem 0.375rem;
  border-radius: 4px;
  font-size: 0.75rem;
  font-weight: bold;
}

.tech-content {
  flex: 1;
  background: rgba(0, 0, 0, 0.4);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  padding: 1rem;
}

.tech-tree {
  height: 600px;
  overflow: auto;
}

.tree-container {
  width: 100%;
  height: 100%;
}

.tree-svg {
  width: 100%;
  height: 100%;
}

.connection-line {
  stroke: rgba(255, 255, 255, 0.2);
  stroke-width: 2;
  fill: none;
}

.connection-line.available {
  stroke: rgba(0, 212, 255, 0.5);
}

.connection-line.researched {
  stroke: #00ff88;
}

.tech-node {
  cursor: pointer;
  transition: all 0.2s ease;
}

.tech-node:hover .node-circle {
  stroke-width: 3;
}

.node-circle {
  fill: rgba(255, 255, 255, 0.1);
  stroke: rgba(255, 255, 255, 0.3);
  stroke-width: 2;
}

.tech-node.available .node-circle {
  fill: rgba(0, 212, 255, 0.2);
  stroke: #00d4ff;
}

.tech-node.researched .node-circle {
  fill: rgba(0, 255, 136, 0.2);
  stroke: #00ff88;
}

.tech-node.locked .node-circle {
  fill: rgba(128, 128, 128, 0.1);
  stroke: rgba(128, 128, 128, 0.3);
}

.node-icon {
  font-size: 20px;
  fill: #ffffff;
  dominant-baseline: middle;
}

.node-name {
  font-size: 12px;
  fill: #cccccc;
  dominant-baseline: middle;
}

.tech-node.available .node-name {
  fill: #00d4ff;
}

.tech-node.researched .node-name {
  fill: #00ff88;
}

.list-filters {
  display: flex;
  gap: 0.5rem;
  align-items: center;
  margin-bottom: 1rem;
}

.sort-select {
  padding: 0.375rem 0.75rem;
  background: rgba(0, 0, 0, 0.4);
  color: #ffffff;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 4px;
  font-size: 0.875rem;
}

.filter-btn {
  padding: 0.375rem 0.75rem;
  background: rgba(255, 255, 255, 0.1);
  color: #cccccc;
  border: none;
  border-radius: 4px;
  font-size: 0.875rem;
  cursor: pointer;
  transition: all 0.2s ease;
}

.filter-btn:hover {
  background: rgba(255, 255, 255, 0.2);
}

.filter-btn.active {
  background: #00d4ff;
  color: #000000;
}

.tech-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 1rem;
  max-height: 600px;
  overflow-y: auto;
}

.research-queue {
  background: rgba(0, 0, 0, 0.4);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  padding: 1rem;
}

.queue-list {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.queue-item {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 0.75rem;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 6px;
}

.queue-info {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  flex: 1;
}

.queue-icon {
  font-size: 1.5rem;
}

.queue-details {
  flex: 1;
}

.queue-name {
  font-weight: 500;
  color: #ffffff;
  margin-bottom: 0.25rem;
}

.queue-category {
  font-size: 0.875rem;
  color: #888888;
}

.queue-cost {
  display: flex;
  gap: 0.5rem;
}

.cost-item {
  display: flex;
  align-items: center;
  gap: 0.25rem;
  padding: 0.25rem 0.5rem;
  background: rgba(0, 212, 255, 0.1);
  border-radius: 4px;
  font-size: 0.875rem;
  color: #00d4ff;
}

.cost-icon {
  font-size: 1rem;
}

.cost-amount {
  font-weight: 500;
}

.queue-actions {
  display: flex;
  gap: 0.25rem;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .tech-stats {
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  }
  
  .tech-grid {
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  }
}

@media (max-width: 768px) {
  .technology-view {
    padding: 0.5rem;
    gap: 1rem;
  }
  
  .overview-header {
    flex-direction: column;
    align-items: stretch;
    gap: 0.5rem;
  }
  
  .overview-actions {
    justify-content: center;
  }
  
  .category-tabs {
    justify-content: center;
  }
  
  .research-card {
    flex-direction: column;
    align-items: stretch;
    gap: 0.75rem;
  }
  
  .research-progress {
    min-width: auto;
  }
  
  .list-filters {
    flex-direction: column;
    align-items: stretch;
  }
  
  .tech-grid {
    grid-template-columns: 1fr;
  }
  
  .queue-item {
    flex-direction: column;
    align-items: stretch;
    gap: 0.75rem;
  }
  
  .queue-actions {
    justify-content: center;
  }
}
</style>